package nettyTest.netty3Test.codecTest1.codeTest1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

/**
 * @author Administrator encode Integer ==> String decode String ==> Integer
 * String这种还是用原生的docode
 * 泛型的类型只是encode 和 decode 的类型，并不是编码和解码后的类型
 */
public class MyMessageToMessageCodec2 extends MessageToMessageCodec<ByteBuf, Integer> {

    /**
     * decode 会根据接受的数据，调用多次，知道确定没有新的元素添加到list或者Bytebuf没有更多的读字节为止，如果list out不为空，
     * 就将list传递给下一个channelInboundHandler处理，该处理器方法也会调用多次。
     *
     * @param ctx
     * @param msg
     * @param out
     * @throws Exception
     */

    @Override
    protected void encode(ChannelHandlerContext ctx, Integer msg, List<Object> out) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("========***************MyMessageToMessageCodec2 encode Integer msg " + msg);
        io.netty.buffer.ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.directBuffer(4);
        byteBuf.writeInt(msg);
        out.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        // TODO Auto-generated method stub
        Integer integer = Integer.valueOf(msg.readInt());
        System.out.println("========***************MyMessageToMessageCodec2 decode ByteBuf to String " + integer);
        out.add(String.valueOf(integer));
    }

}
